package com.chaodev.base.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.dto.VolunteerDto;
import com.chaodev.base.model.Result;
import com.chaodev.base.model.ResultEnum;
import com.chaodev.base.model.UserInfo;
import com.chaodev.base.model.Volunteer;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.service.VolunteerService;
import com.chaodev.base.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/volunteer")
@Api(tags = "志愿者管理相关接口")
public class VolunteerController {
    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILogService logService;
    @Autowired
    private VolunteerService volunteerService;

    /**
     * 获取志愿者信息表列表分页
     */
    @ApiOperation(value = "获取志愿者信息表列表分页", notes = "获取志愿者信息表列表分页")
    @PostMapping(value = {"/list"})
    public Result list(@RequestBody VolunteerDto dto, HttpServletRequest request) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Volunteer volunteer = new Volunteer();
            BeanUtil.copyProperties(dto, volunteer);
            if (null == dto.getPage()) {
                dto.setPage(1);
            }
            if (null == dto.getRows()) {
                dto.setRows(20);
            }
            PageInfo<Volunteer> volunteerList = volunteerService.queryPageList(dto.getPage(), dto.getRows(), volunteer);
            result.setCode(200);
            result.setMsg("获取成功");
            result.setData(volunteerList);
            logService.logAdd(null, "获取志愿者信息表列表分页", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(null, "获取志愿者信息表列表分页", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * 获取志愿者信息表对象
     */
    @ApiOperation(value = "获取志愿者信息表对象", notes = "获取志愿者信息表对象")
    @GetMapping("/getDataById")
    public Result findById(Integer id, HttpServletRequest request) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Volunteer dataById = null;
            if (id != null) {
                dataById = volunteerService.findDataById(id);
            } else {
                dataById = volunteerService.findDataByUserId(userInfo.getUserId());
                if (dataById == null) {
                    result.setCode(ResultEnum.SUCCESS.getCode());
                    result.setMsg("该用户尚未注册成为志愿者");
                    result.setData(dataById);
                    return result;
                }
            }
            result.setCode(200);
            result.setData(dataById);
            logService.logAdd(null, "获取志愿者信息表对象", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(null, "获取志愿者信息表对象", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * 保存志愿者信息表对象
     */
    @ApiOperation(value = "保存志愿者信息表对象", notes = "保存志愿者信息表对象")
    @PostMapping(value = {"/save"})
    public Result save(@RequestBody Volunteer volunteer, HttpServletRequest request) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Volunteer volunteer1 = volunteerService.findDataByUserId(volunteer.getRealAccNbr());
            if(null!=volunteer.getId()&&volunteer.getId()>0){
                if(volunteer1==null){
                    return Result.error(ResultEnum.NODATE.getData(),ResultEnum.NODATE);
                }
            }else{
                if(volunteer1!=null){
                    return Result.error("号码已被注册，请不要重复注册");
                }
            }
            volunteerService.saveData(volunteer, userInfo);

            result.setCode(200);
            result.setMsg("操作成功");
            result.setData(volunteer);
            logService.logAdd(null, "保存志愿者信息表对象", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(null, "保存志愿者信息表对象", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @ApiOperation(value = "保存志愿者信息表对象(无tonken)", notes = "保存志愿者信息表对象(无tonken)")
    @PostMapping(value = {"/saveOut"})
    public Result saveOut(@RequestBody Volunteer volunteer, HttpServletRequest request) {
        Result result = new Result();
        UserInfo userInfo = new UserInfo();
        if (StrUtil.isEmpty(volunteer.getUserId())) {
            volunteer.setUserId(volunteer.getRealAccNbr());
        }
        userInfo.setUserId(volunteer.getUserId());
        userInfo.setUserName(volunteer.getUserName());
        Volunteer volunteer1 = volunteerService.findDataByUserId(volunteer.getRealAccNbr());
        if(null!=volunteer.getId()&&volunteer.getId()>0){
            if(volunteer1==null){
                return Result.error(ResultEnum.NODATE.getData(),ResultEnum.NODATE);
            }
        }else{
            if(volunteer1!=null){
                return Result.error("号码已被注册，请不要重复注册");
            }
        }
        volunteerService.saveData(volunteer, userInfo);
        result.setCode(200);
        result.setMsg("操作成功");
        result.setData(volunteer);
        logService.logAdd(null, "保存志愿者信息表对象", "SUCCESS", result.toString(), null, request);
        return result;
    }

    /**
     * 删除志愿者实体类对象
     */
    @ApiOperation(value = "删除志愿者信息表对象", notes = "删除志愿者信息表对象")
    @GetMapping(value = {"/del"})
    public Result delete(@RequestParam List<Integer> ids, HttpServletRequest request) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            volunteerService.deleteDataById(ids);
            result.setCode(200);
            logService.logAdd(null, "删除志愿者信息表对象", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(null, "删除志愿者信息表对象", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * 查看志愿者公约
     */
    @ApiOperation(value = "查看志愿者公约", notes = "查看志愿者公约")
    @PostMapping("/readFile")
    public Result getFileById(String filePath, HttpServletRequest request) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = null;
        if (filePath == null || filePath == " ") {
            result.setCode(500);
            result.setMsg("缺少参数");
            logService.logAdd(null, "查看志愿者公约", "ERROR", result.toString(), userInfo, request);
        }
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            result.setCode(200);
            result.setMsg("获取成功");
            result.setData(filePath);
            logService.logAdd(null, "查看志愿者公约", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(null, "查看志愿者公约", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/getVolunteerStatistic")
    @ApiOperation(value = "获取志愿者统计数据")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getVolunteerStatistic(@RequestBody Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {
        Result result = Result.success(null, "查询成功");
        String token = request.getHeader("token");
        Result logResult = new Result();
        UserInfo userInfo = new UserInfo();
        try {
            if (!redisDao.existsKey(token)) {
                result.setCode(ResultEnum.EREOR.getCode());
                result.setMsg("登录超时");
                return result;
            }

            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            result.setData(volunteerService.getVolunteerStatistic(userInfo.getUserId()));
        } catch (Exception exception) {
            result.setCode(ResultEnum.UNKNOWNERROR.getCode());
            result.setMsg("发生错误:" + exception.getMessage());
        } finally {
            BeanUtils.copyProperties(result, logResult);
            logResult.setData(null);
            String resultCode = logResult.getCode().equals(ResultEnum.SUCCESS.getCode()) ? "SUCCESS" : "ERROR";
            logService.logAdd(map.toString(), "获取志愿者统计数据", resultCode, logResult.toString(), userInfo, request);
        }
        return result;
    }
}
